package com.tange.ai.iot.client.gnssa.utils;

import android.os.Build;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

public class VrThumbnailParser {
    // 常量定义（与C语言一致）
    public static final int THUMBNAIL_NUM = 2;
    public static final int THUMBNAIL_SIZE = 64 * 1024; // 65536
    public static final int STRUCT_SIZE = 131096; // 整个结构体大小

    public static HyVrThumbnailResp parse(byte[] bytes) {
        if (bytes.length < STRUCT_SIZE) {
            throw new IllegalArgumentException("Byte array too small");
        }

        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN); // 根据C端实际情况设置

        // 解析头部
        boolean over = buffer.get() != 0;
        buffer.position(buffer.position() + 3); // 跳过3字节填充
        int num = buffer.getInt();

        // 解析缩略图数组
        List<VrThumbnailJpeg> jpegs = new ArrayList<>();
        for (int i = 0; i < THUMBNAIL_NUM; i++) {
            int size = buffer.getInt();
            int timestamp = buffer.getInt();
            byte[] data = new byte[THUMBNAIL_SIZE];
            buffer.get(data);
            jpegs.add(new VrThumbnailJpeg(size, timestamp, data));
        }

        return new HyVrThumbnailResp(over, num, jpegs);
    }

    // 内部数据类
    public static class VrThumbnailJpeg {
        final int size;
        final int timestamp;
        final byte[] data;

        public VrThumbnailJpeg(int size, int timestamp, byte[] data) {
            this.size = size;
            this.timestamp = timestamp;
            this.data = data;
        }

        // 将二进制数据转为Base64（用于JSON）
        public String getDataBase64() {
            // 只编码实际有效数据部分
            if (size > 0 && size <= data.length) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    return Base64.getEncoder().encodeToString(
                            Arrays.copyOfRange(data, 0, size)
                    );
                }
            }
            return "";
        }
    }

    public static class HyVrThumbnailResp {
        final boolean over;
        final int num;
        final List<VrThumbnailJpeg> jpegs;

        public HyVrThumbnailResp(boolean over, int num, List<VrThumbnailJpeg> jpegs) {
            this.over = over;
            this.num = num;
            this.jpegs = jpegs;
        }
    }
}
